package com.starbucket.user.controller;


import com.starbucket.user.entity.User;
import com.starbucket.user.serivce.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.starbucket.vo.UserResult;


@RestController
@RequestMapping("/user")
public class UserController {

    private String Password_Encryption;

    @Autowired
    private UserService userService;
    BCryptPasswordEncoder passEncoder = new BCryptPasswordEncoder();

    @PostMapping("/login")
    public UserResult<Object> login(User params) {
        User user = userService.login(params);
        // 密码验证
        if (user != null){
            if (passEncoder.matches(params.getPassword(), user.getPassword())) {
                return UserResult.success(user);
            }
            return UserResult.fail("用户名或密码错误");
        }
        return UserResult.notExist("用户不存在");
    }

    @PostMapping("/register")
    public UserResult<Object> register(User params){
        User user = userService.login(params);
        if (user != null){
            return UserResult.fail("用户已存在");
        }
        if (params.getUsername() != null && params.getPassword() != null){
            // 密码加密加盐
            this.Password_Encryption = passEncoder.encode(params.getPassword());
            params.setPassword(this.Password_Encryption);
            int result = userService.register(params);
            if (result > 0){
                return UserResult.success(params);
            }
            return UserResult.fail("注册失败");
        }
        return UserResult.fail("用户密码为空，请重新输入！");
    }

    @PostMapping("/search/{id}")
    public UserResult<Object> search(@PathVariable Integer id){
        if (id != null){
            User user = userService.search(id);
            if (user != null){
                return UserResult.success(user);
            }
            return UserResult.notExist("用户不存在");
        }
        return UserResult.fail("用户ID为空，请重新输入！");
    }


}
